package com.siyoumi.app.modules.app_ess.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.*;
import com.siyoumi.app.modules.app_ess.service.*;
import com.siyoumi.app.modules.app_ess.vo.*;
import com.siyoumi.app.modules.user.service.SvcSysUser;
import com.siyoumi.app.service.EssStudyRecordService;
import com.siyoumi.app.service.EssTestQuestionService;
import com.siyoumi.app.service.EssTestResultItemService;
import com.siyoumi.app.service.EssTestResultService;
import com.siyoumi.component.XBean;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.WxAppApiController;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

//老师接口
@Slf4j
@RestController
@RequestMapping("/wxapp/app_ess/api_teacher")
public class ApiAppEssTeacher
        extends WxAppApiController {
    /**
     * 老师-学习任务列表
     */
    @GetMapping("study_list")
    public XReturn studyList() {
        InputData inputData = InputData.fromRequest();
        String moduleId = inputData.input("module_id");
        XValidator.isNullOrEmpty(moduleId, "miss module_id");

        String[] select = {"estudy_id", "estudy_name", "estudy_date_begin", "estudy_date_end",};
        JoinWrapperPlus<EssStudy> query = SvcEssStudy.getBean().listQuery(inputData);
        query.orderByDesc("estudy_create_date")
                .orderByAsc("estudy_id");

        query.eq("estudy_uid", getUid()); //指定老师
        query.select(select);
        IPage<EssStudy> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), true);
        //list
        IPage<Map<String, Object>> pageData = SvcEssStudy.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        //收集所有ID
        List<String> estudyIds = list.stream().map(item -> (String) item.get("estudy_id")).collect(Collectors.toList());
        List<EssStudyTask> listTask = SvcEssStudy.getBean().getTaskList(estudyIds); //子任务列表
        //
        for (Map<String, Object> item : list) {
            EssStudy entity = XBean.fromMap(item, EssStudy.class);
            item.put("id", entity.getKey());
            item.put("state", SvcEssStudy.getBean().getState(entity));

            List<EssStudyTask> tasks = listTask.stream().filter(i -> i.getEstask_study_id().equals(entity.getKey())).collect(Collectors.toList());
            item.put("tasks", tasks);
        }

        getR().setData("list", list);
        getR().setData("total", pageData.getTotal());

        return getR();
    }

    /**
     * 老师-学习任务-子任务列表
     */
    @GetMapping("study_task_list")
    public XReturn studyTaskList() {
        InputData inputData = InputData.fromRequest();
        String studayId = inputData.input("studay_id");
        XValidator.isNullOrEmpty(studayId, "缺少学习任务ID");
        String taskId = inputData.input("task_id");
        XValidator.isNullOrEmpty(taskId, "缺少子任务ID");
        String name = inputData.input("name");

        String[] select = {"user_id", "user_name", "esre_fun", "esre_state", "esre_state_date",};
        JoinWrapperPlus<EssStudyRecord> query = SvcEssStudy.getBean().listRecordQuery(inputData); //子任务列表
        query.join(SysUser.table(), SysUser.tableKey(), "esre_uid");
        query.select(select);
        if (XStr.hasAnyText(name)) { //学生名字
            query.like("user_name", name);
        }
        IPage<EssStudyRecord> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = EssStudyRecordService.getBean().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        getR().setData("list", list);

        return getR();
    }

    /**
     * 老师-添加学习任务
     */
    @PostMapping("study_add")
    public XReturn studyAdd(@Validated @RequestBody VoEssStudyAdd vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);

        vo.setEstudy_uid(getUid());
        return SvcEssStudy.getBean().add(vo);
    }

    /**
     * 老师-删除学习任务
     */
    @PostMapping("study_del")
    @Transactional(rollbackFor = Exception.class)
    public XReturn studyDel() {
        XValidator.isNullOrEmpty(getID(), "miss id");
        return SvcEssStudy.getBean().delete(getID(), false);
    }


    /**
     * 评测列表
     */
    @GetMapping("test_list")
    public XReturn testList() {
        InputData inputData = InputData.fromRequest();

        String[] select = {"etest_id",
                "etest_create_date",
                "etest_title",
                "etest_date_begin",
                "etest_date_end",
                "etest_test_minute",
                "etest_test_not_submit",
                "etest_test_end_remind",
                "etest_random",
                "etest_score_show",
                "etest_submit_total",
                "etest_test_total",
                "etest_fun_total",
                "etest_question_total",
                "etest_state",
                "etest_state_date",
                "etest_send_fun",
                "etest_send_fun_date",
        };
        JoinWrapperPlus<EssTest> query = SvcEssTest.getBean().listQuery(inputData);
        query.eq("etest_uid", getUid()); //指定老师
        query.select(select);
        query.orderByDesc("etest_id");
        IPage<EssTest> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), true);
        //list
        IPage<Map<String, Object>> pageData = SvcEssTest.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        for (Map<String, Object> item : list) {
            EssTest entity = XBean.fromMap(item, EssTest.class);
            item.put("id", entity.getKey());
            //状态
            XReturn rState = SvcEssTest.getBean().getState(entity);
            item.put("state", rState);
        }

        getR().setData("list", list);
        getR().setData("total", pageData.getTotal());

        return getR();
    }

    /**
     * 老师-添加评测
     */
    @PostMapping("test_add")
    public XReturn testAdd(@Validated @RequestBody VoEssTestAdd vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);

        InputData inputData = InputData.fromRequest();
        vo.setEtest_uid(getUid());
        return SvcEssTest.getBean().add(inputData, vo);
    }


    /**
     * 老师-添加学生
     */
    @PostMapping("test_add_student")
    public XReturn testAddStudent(@Validated @RequestBody VoEssTestAddStudent vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);
        return SvcEssTest.getBean().addStudent(vo);
    }

    /**
     * 老师-添加题目
     */
    @PostMapping("test_add_question")
    public XReturn testAddQuestion(@Validated @RequestBody VoEssTestBatchAddQuestion vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);
        return SvcEssTest.getBean().batchAddQuestion(vo);
    }

    /**
     * 老师-删除题目
     *
     * @param vo
     * @param result
     */
    @PostMapping("test_del_question")
    public XReturn testDelQuestion(@Validated VoEssTestQuestionDel vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);
        return SvcEssTest.getBean().delQuestion(vo);
    }

    /**
     * 添加单题目，或者修改积分
     *
     * @param vo
     * @param result
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/test_question_save")
    public XReturn save(@Validated VoEssTestQuestion vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);
        //
        InputData inputData = InputData.fromRequest();
        return SvcEssTest.getBean().editQuestion(inputData, vo);
    }

    /**
     * 删除评测
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/test_del")
    public XReturn testDel() {
        return SvcEssTest.getBean().delete(getIds());
    }

    /**
     * 发布评测
     */
    @PostMapping("/test_audit")
    public XReturn testAudit(@Validated VoEssTestAudit vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);

        return SvcEssTest.getBean().audit(vo);
    }

    /**
     * 复制评测
     */
    @PostMapping("/test_copy")
    public XReturn testCopy(@Validated VoEssTestCopy vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);

        return SvcEssTest.getBean().copy(vo);
    }

    /**
     * 加时
     */
    @PostMapping("/test_add_time")
    public XReturn addTime(@Validated VoEssTestAddTime vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);

        return SvcEssTest.getBean().addTime(vo);
    }

    /**
     * 公布成绩
     */
    @PostMapping("/test_show_result")
    public XReturn showResult(@Validated VoEssTestShowResult vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true);

        return SvcEssTest.getBean().showResult(vo);
    }


    /**
     * 学生列表
     */
    @GetMapping("student_list")
    public XReturn studentList() {
        InputData inputData = InputData.fromRequest();
        String testId = inputData.input("test_id");

        List<String> classIds = SvcEssClass.getBean().getClassIds(getUid()); //获取老师所有班级
        String[] select = {
                "user_id",
                "user_name",
                "user_headimg",
                "eclass_id",
                "eclass_name",
                "euser_module_count",
                "euser_module_fun",
                "euser_test1_count",
                "euser_test1_fun",
        };
        JoinWrapperPlus<EssUser> query = SvcEssUser.getBean().listQuery(0);
        query.join(EssClassUser.table(), "user_id", "ecu_uid");
        query.join(EssClass.table(), EssClass.tableKey(), "ecu_class_id");
        query.in("ecu_class_id", classIds)
                .eq("user_enable", 1);
        ;
        query.select(select);
        query.orderByAsc("ecu_class_id")
                .orderByAsc("user_id");
        if (XStr.hasAnyText(testId)) { //评测已配置的学生
            String sqlExists = "SELECT 1 FROM wx_app_x.t_ess_test_student WHERE etcla_test_id = {0} AND etcla_uid = user_id";
            query.exists(sqlExists, testId);
        }

        IPage<EssUser> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = SvcEssUser.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        //
        for (Map<String, Object> item : list) {
        }

        getR().setData("list", list);
        //getR().setData("count", pageData.getTotal());
        return getR();
    }

    /**
     * 老师列表
     */
    @GetMapping("teacher_list")
    public XReturn teacherList() {
        InputData inputData = InputData.fromRequest();

        String[] select = {
                "user_id",
                "user_name",
                "user_headimg",
        };
        JoinWrapperPlus<EssUser> query = SvcEssUser.getBean().listQuery(1);
        query.eq("user_enable", 1)
                .ne("user_id", getUid());
        query.select(select);
        query.orderByAsc("user_id");
        IPage<EssUser> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = SvcEssUser.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        //
        for (Map<String, Object> item : list) {
        }

        getR().setData("list", list);
        //getR().setData("count", pageData.getTotal());
        return getR();
    }
}

